package com.ruoyi.common.wx;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class StreamUtils {

    /**
     * 将输入流转换为字符串。
     *
     * @param inputStream 输入流
     * @param charsetName 字符集名称，默认使用 UTF-8
     * @return 转换后的字符串
     * @throws IOException 如果发生 I/O 错误
     */
    public static String inputStream2String(InputStream inputStream, String charsetName) throws IOException {
        if (inputStream == null) {
            return null;
        }
        StringBuilder resultStringBuilder = new StringBuilder();
        // 使用指定的字符集名称来创建 InputStreamReader，默认为 UTF-8
        try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, charsetName != null ? charsetName : StandardCharsets.UTF_8.name()))) {
            String line;
            while ((line = br.readLine()) != null) {
                resultStringBuilder.append(line);
            }
        }
        return resultStringBuilder.toString();
    }

}